import React, { useEffect, useRef, useState } from "react";
import { Table, Row, Col, Input, Form, Button, Switch, Space, Divider, Image, message, Modal, Select, QRCode } from 'antd'
import Prefix from '../../components/prefix'
import { SearchOutlined, PlusOutlined } from '@ant-design/icons';
import * as apis from '../../lib/api'
import http from '../../lib/http'
import _ from 'lodash'
import Add from './add'
import { useNavigate } from "react-router-dom";
import { handleValue } from '../../components/upload'



const Index = () => {
    const [search, setSearch] = useState({page: 1,page_size: 20})
    const [loading, setLoading] = useState(false)
    const [data, setData] = useState()
    const [seleckeys, setSeleckeys] = useState([])
    const [category, setCategory] = useState([])
    const n = useNavigate()

    const addRef = useRef()

    const loadData = async (s) => {
        try {
            const data = await http.post(apis.PRODUCT_LIST,s)
            for(let i=0;i<data?.list?.length;i++){
                if(data.list[i].materials){
                    data.list[i].materials = JSON.parse(data.list[i].materials)
                }
            }
           
            setData(data)
            setSeleckeys([])
        } catch (error) {
            
        }
    }

    const onSearch = async (values) => {
        let cpSearch = {...search}
        cpSearch.name = values?.name
        cpSearch.category_id = values?.category_id
        cpSearch.page = 1
        cpSearch.status = values?.status
        setLoading(true)
        await loadData(cpSearch)
        setLoading(false)
        setSearch(cpSearch)
    }

    const pageSearch = async (page,page_size) => {
        let cpSearch = {...search}
        cpSearch.page_size = page_size
        cpSearch.page = page
        setLoading(true)
        await loadData(cpSearch)
        setLoading(false)
        setSearch(cpSearch)
    }

    const showChange = async (checked,v) => {
        const cpData = _.cloneDeep(data)     
        const index = cpData?.list?.findIndex(m => m.id === v.id)
        if(index !== -1){
            cpData.list[index].status = checked ? 1:2
            setLoading(true)
            try {
                await http.post(apis.PRODUCT_SHOW_UPDATE,{id: v.id,status: cpData.list[index].status})
                setData(cpData)
            } catch (error) {
                
            }
            setLoading(false)
        }
    }

    const del = async (ids) => {
        setLoading(true)
        try {
            await http.post(apis.PRODUCT_DELETE,{ids})
            message.success("操作成功")
            await loadData(search)
        } catch (error) {
            
        }
        setLoading(false)
    }

    const add = () => {
        addRef.current.setIsModalOpen(true)
        addRef.current.resetFields()
        addRef.current.setFieldsValue({})
    }

    const edit = (v) => {
        addRef.current.setIsModalOpen(true)
        addRef.current.resetFields()

        if(v.imgs && typeof v.imgs !== "object"){
            v.imgs = JSON.parse(v.imgs)
        }


        addRef.current.setFieldsValue({id: v.id,category_id: v.category_id,tags: (v?.tags && v?.tags?.length !== 0) ? v?.tags?.split(","):[],name: v?.name,imgs: handleValue(v.imgs), cover: handleValue(v?.cover),price_str: (v.price/100).toFixed(2) })
    }

    const onRefresh = async (isInit) => {
        if(!isInit){
            setLoading(true)
            await loadData(search)
            setLoading(false)
            return
        }
        let cpSearch = {...search}
        cpSearch.page = 1
        setLoading(true)
        await loadData(cpSearch)
        setLoading(false)
        setSearch(cpSearch)
    }

    useEffect(()=>{
        setLoading(true)
        loadData(search).then(r => {
            setLoading(false)
        })

        http.post(apis.PRODUCT_CATEGORY_LIST,{page: 1,page_size: 100,status: 1}).then(r => {
            setCategory(r?.list)
        })
        // eslint-disable-next-line
    },[])

    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            width: 50
        },
        {
            title: '名字',
            dataIndex: 'name',
            key: 'name'
        },
        {
            title: '标签',
            dataIndex: 'tags',
            key: 'tags'
        },
        {
            title: '定价',
            dataIndex: 'price',
            key: 'price',
            render: (v,r) => (
                <>
                    <div>
                        <div>基础价格：¥ {(v/100).toFixed(2)}</div>
                        {
                            r?.materials?.cutparts?.map(i => (
                                <div key={i.code}>{i.txt}印刷：¥ {i.price}</div>
                            ))
                        }
                    </div>
                </>
            )
        },
        {
            title: '所属分类',
            dataIndex: 'category_id',
            key: 'category_id',
            render: (v) => (
                <span>{category?.find(item => item.id === v)?.name}</span>
            )
        },
        {
            title: '封面图',
            dataIndex: 'cover',
            key: 'cover',
            render: (v) => (
                <Image src={process.env.REACT_APP_OSS_URL+v+"?x-oss-process=image/resize,w_300"} width={60} height={60} fallback="" />
            )
        },
        {
            title: '上架状态',
            dataIndex: 'status',
            key: 'status',
            render: (v,r) => (
                <Switch checked={v === 1} checkedChildren="下架" unCheckedChildren="上架" onChange={(e) => showChange(e,r)} />
            )
        },
        {
            title: '创建时间',
            dataIndex: 'created_at',
            key: 'created_at'
        },
        {
            title: '模型配置',
            dataIndex: 'materials',
            key: 'materials',
            render: (v) => (
                v ? <span style={{color: "green"}}>已配置</span>:<span style={{color: "red"}}>未配置</span>
            )
        },
        {
            title: '操作',
            dataIndex: 'a',
            key: 'a',
            render: (v,r) => (
                <>
                    <Button loading={loading} type="link" onClick={()=> n(`/product/mconfig?id=${r.id}`)} style={{padding: 0}}>模型配置</Button>
                    <Divider type="vertical" />
                    <Button loading={loading} type="link" onClick={()=> edit(r)} style={{padding: 0}}>编辑</Button>
                    <Divider type="vertical" />
                    <Button loading={loading} type="link" onClick={()=>{
                        Modal.confirm({
                            content: <QRCode size={370} value={`${process.env.REACT_APP_H5_URL}/design/${r.id}`} />,
                            icon: <></>
                        })
                    }} style={{padding: 0}}>二维码</Button>
                    <Divider type="vertical" />
                    <Button loading={loading} style={{padding: 0}} type="link" danger onClick={()=> {
                         Modal.confirm({
                            title: "提示",
                            content: <p>确定删除吗?</p>,
                            onOk: async () => {
                                await del([r.id])
                            }
                        })
                    }}>删除</Button>
                </>
            )
        }
    ]

    return (
        <div>
            <Add category={category} funcs={addRef} onRefresh={onRefresh} />
            <Form onFinish={onSearch}>
                <Row gutter={16}>
                    <Col span={8}>
                        <Form.Item name="name">
                            <Prefix label="名称">
                                <Input allowClear placeholder="请输入名称或标签名称" />
                            </Prefix>
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item name="category_id">
                            <Prefix label="所属分类">
                                <Select allowClear placeholder="请选择">
                                    {
                                        category?.map(v => (
                                            <Select.Option key={v.id} value={v.id}>{v.name}</Select.Option>
                                        ))
                                    }
                                </Select>
                            </Prefix>
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item name="status">
                            <Prefix label="售卖状态">
                                <Select allowClear placeholder="请选择">
                                    <Select.Option value={1}>已上架</Select.Option>
                                    <Select.Option value={2}>已下架</Select.Option>
                                </Select>
                            </Prefix>
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={16}>
                    <Col span={8}>
                        <Form.Item>
                            <Space>
                                <Button loading={loading} type="primary" htmlType="submit" icon={<SearchOutlined />}>查询</Button>
                                <Button onClick={add} loading={loading} ghost type="primary" icon={<PlusOutlined />}>新增产品</Button>
                            </Space>
                        </Form.Item>
                    </Col>
                </Row>
            </Form>
            <Space>
                <span>已选 {seleckeys?.length} 条</span>
                <Button danger disabled={seleckeys?.length === 0} onClick={() => {
                    Modal.confirm({
                        title: "提示",
                        content: <p>确定删除 <span style={{color: 'red'}}>{seleckeys?.length}条</span> 数据吗?</p>,
                        onOk: async () => {
                            await del(seleckeys)
                        }
                    })
                }}>批量删除</Button>
            </Space>
            <div style={{height: 12}}></div>
            <Table 
                rowKey={'id'}
                dataSource={data?.list || []} 
                loading={loading} 
                columns={columns}
                pagination={{
                    showQuickJumper: true,
                    showSizeChanger: true,
                    onChange: pageSearch,
                    total: data?.total,
                    current: data?.page,
                    pageSize: data?.page_size
                }}
                scroll={{
                    y: 'calc(100vh - 510px)'
                }}
                rowSelection={{
                    onChange: (keys) => {
                        setSeleckeys(keys)
                    },
                    selectedRowKeys: seleckeys
                }}
            />
        </div>
    )
}

export default Index